// const autojsUtils = require('./modules/autojs-utils');
// momo fcfa ui
"ui";

const Constant = require("./constant.js");

auto();

device.keepScreenOn();

// 之前保存的钱包
Constant.initMtnAndPin();
// let preWalletNumber = storages.create(Constant.WALLET_NAME).get(Constant.WALLET_NUMBER) || "";
// let preWalletPin = storages.create(Constant.WALLET_NAME).get(Constant.WALLET_PIN) || "";

ui.layout(
    <vertical>
        <text id="sceneName"
            w="*"
            h="auto"
            gravity="center"
            marginTop="16"
            textColor="red"
            textStyle="bold"
            textSize="16"
            text={Constant.WALLET_MTN_FCFA_NAME} />

        <input id="wallet"
            marginTop="16"
            hint="请输入钱包号码, 带0开头"
            text={Constant.getMtn()}
            textSize="14" />

        <input id="pin"
            marginTop="16"
            hint="请输入钱包PIN"
            text={Constant.getPin()}
            textSize="14" />

        <button id="saveAndStart"
            marginTop="16"
            text="保存钱包号并启动脚本" />

        <button id="saveOnly"
            marginTop="10"
            text="仅保存钱包号" />

    </vertical>
);

ui.saveAndStart.click(function () {
    var name = ui.wallet.text();
    var pin = ui.pin.text();

    if (!name || (name.length <= 8)) {
        // main();
        toast("saveWalletAndStart: 钱包号错误!");
        return;
    }

    if (!pin || (pin.length <= 2)) {
        // main();
        toast("saveWalletAndStart: pin错误!");
        return;
    }

    // 保存本地
    Constant.setMtn(name);
    Constant.setPin(pin);

    toast(name + "," + pin + " 已启动脚本 saveAndStart");

    setTimeout(() => {
        // 启动脚本
        threads.start(function () {
            //在新线程执行的代码
            main();
        });
    }, 2000);
});

ui.saveOnly.click(function () {
    var name = ui.wallet.text();
    var pin = ui.pin.text();

    if (!name || (name.length <= 8)) {
        // main();
        toast("saveOnly: 钱包号错误!");
        return;
    }

    if (!pin || (pin.length <= 2)) {
        // main();
        toast("saveOnly: pin错误!");
        return;
    }

    // 保存本地
    Constant.setMtn(name);
    Constant.setPin(pin);

    toast(name + "," + pin + " 已保存 saveOnly");
});


const BaseSmsUtil = require("./baseSmsUtil.js");
const BaseApiUrl = require("./baseApiUrl.js");
const BaseHttpUtil = require("./baseHttpUtil.js");

const MomoFcfaAppOpen = require("./momoFcfaAppOpen.js");
const MomoFcfaPageUtil = require("./momoFcfaPageUtil.js");
const MomoFcfaFunAction = require("./momoFcfaFunAction.js");


// 测试转账
// let testMtnTransfer = true;

// 转账信息
let targetMtnTransferAmount = "";
let targetMtnTransferId = "";
let targetMtnTransferAccount = "";
let targetMtnTransferReference = "";

const initMtnTransfer = (data) => {
    targetMtnTransferAmount = data.amount + "";
    targetMtnTransferId = data.id + "";
    targetMtnTransferAccount = data.mtn + "";
    targetMtnTransferReference = data.reference + "";
}

const isValidMtnTransfer = () => {
    let result1 = targetMtnTransferAmount || "";
    let result2 = targetMtnTransferId || "";
    let result3 = targetMtnTransferAccount || "";

    return ((result1.length > 0) && (result2.length > 0) && (result3.length > 0));
}

const cleanMtnTransfer = () => {
    targetMtnTransferAmount = "";
    targetMtnTransferId = "";
    targetMtnTransferAccount = "";
    targetMtnTransferReference = "";
}

const printMtnTransferLog = () => {
    console.log(Constant.UI_SDK_VERSION + "targetMtnTransferAmount: " + targetMtnTransferAmount + ",\ntargetMtnTransferId: " + targetMtnTransferId + ",\ntargetMtnTransferAccount: " + targetMtnTransferAccount + ",\ntargetMtnTransferReference: " + targetMtnTransferReference);
}

/** 启动脚本逻辑 */
function main() {
    // 设置坐标宽高
    // setScreenMetrics(720, 1640);
    console.log("w:" + device.width + " ,h:" + device.height);

    // 程序结束自动 隐藏控制台
    console.show(false);
    // --temp close
    if (false) {
        console.setMaxLines(15);
    }

    // 是否需要重启app
    let isNeedRestartWalletApp = false;

    // 是否需要重启脚本
    let isNeedRestartScript = false;

    // 上传短信
    BaseSmsUtil.syncSmsData();

    console.log(Constant.UI_SDK_VERSION + "当前设备: " + Constant.getMtn());
    // sleep(5 * 1000);

    // momo 钱包
    MomoFcfaAppOpen.openMomoApp();

    // 上传短信 
    BaseSmsUtil.syncSmsData();
    sleep(2 * 1000);

    // 测试 --- temp close
    let testTimes = 0;

    while (true) {
        testTimes += 1;
        if (testTimes > 5) {
            console.log("======= 测试结束, 停止脚本");
            return;
        }
        console.log("======== testTimes:" + testTimes);
        // sleep(5000);

        // 清空转账信息
        cleanMtnTransfer();

        // 页面状态
        let pageStatus = MomoFcfaPageUtil.doCheckPageStatus();
        let isLoginPage = pageStatus.isLoginPage;
        let isPinPage = pageStatus.isLoginPinPage;
        let isHomePage = pageStatus.isHomePage;
        let isSendMoneyPage = pageStatus.isSendMoneyMtnPage;
        let isMtnMoMoAccountInputPage = pageStatus.isSendMoneyMtnAccountInputPage;
        let isMtnMoMoAccountConfirmPage = pageStatus.isSendMoneyMtnAccountConfirmPage;
        let isMtnMoMoTransferSuccessPage = pageStatus.isSendMoneyMtnSuccessPage;
        let isMtnMoMoTransferFailPage = pageStatus.isSendMoneyMtnFailPage;
        let isBillSeeAllPage = false;
        let isBillListPage = false;

        // 初始化页面标识
        // isLoginPage = MomoFcfaPageUtil.isLoginPage();
        // isPinPage = MomoFcfaPageUtil.isLoginPinPage();
        // isHomePage = MomoFcfaPageUtil.isHomePage();
        // isBillSeeAllPage = MomoFcfaPageUtil.isSelectAllPage();
        // isBillListPage = MomoFcfaPageUtil.isTransactionListPage();

        if (isLoginPage) {
            // 置空其它标识
            isLoginPage = true;
            isPinPage = false;
            isHomePage = false;
            isSendMoneyPage = false;
            isMtnMoMoAccountInputPage = false;
            isMtnMoMoAccountConfirmPage = false;
            isMtnMoMoTransferSuccessPage = false;
            isMtnMoMoTransferFailPage = false;
            isBillSeeAllPage = false;
            isBillListPage = false;

        } else if (isPinPage) {
            // 置空其它标识
            isLoginPage = false;
            isPinPage = true;
            isHomePage = false;
            isSendMoneyPage = false;
            isMtnMoMoAccountInputPage = false;
            isMtnMoMoAccountConfirmPage = false;
            isMtnMoMoTransferSuccessPage = false;
            isMtnMoMoTransferFailPage = false;
            isBillSeeAllPage = false;
            isBillListPage = false;

        } else if (isHomePage) {
            // 置空其它标识
            isLoginPage = false;
            isPinPage = false;
            isHomePage = true;
            isSendMoneyPage = false;
            isMtnMoMoAccountInputPage = false;
            isMtnMoMoAccountConfirmPage = false;
            isMtnMoMoTransferSuccessPage = false;
            isMtnMoMoTransferFailPage = false;
            isBillSeeAllPage = false;
            isBillListPage = false;

        } else if (isBillSeeAllPage) {
            // 置空其它标识
            isLoginPage = false;
            isPinPage = false;
            isHomePage = false;
            isSendMoneyPage = false;
            isMtnMoMoAccountInputPage = false;
            isMtnMoMoAccountConfirmPage = false;
            isMtnMoMoTransferSuccessPage = false;
            isMtnMoMoTransferFailPage = false;
            isBillSeeAllPage = true;
            isBillListPage = false;

        } else if (isBillListPage) {
            // 置空其它标识
            isLoginPage = false;
            isPinPage = false;
            isHomePage = false;
            isSendMoneyPage = false;
            isMtnMoMoAccountInputPage = false;
            isMtnMoMoAccountConfirmPage = false;
            isMtnMoMoTransferSuccessPage = false;
            isMtnMoMoTransferFailPage = false;
            isBillSeeAllPage = false;
            isBillListPage = true;
        }

        // 判断是否在 momo 应用内
        let isInMomoApp = true;
        //MomoFcfaPageUtil.isInMomoApp();
        if (!isInMomoApp) {
            sleep(1 * 1000);
            home();
            sleep(2 * 1000);
            MomoFcfaAppOpen.openMomoApp();

            // 上传短信
            BaseSmsUtil.syncSmsData();
            sleep(1 * 1000);

            // 清空控制台
            // console.clear();
            continue;
        }

        // 上传短信
        BaseSmsUtil.syncSmsData();
        // sleep(1 * 1000);

        // 获取脚本状态信息 -- temp close
        if (false) {
            let url = BaseApiUrl.checkOperStatus();
            let checkOperStatusParams = { phone: Constant.getMtn() }
            let checkOperStatusResult = BaseHttpUtil.sendPostSync(url, checkOperStatusParams)
            if (checkOperStatusResult !== null) {
                isNeedRestartWalletApp = checkOperStatusResult.momo || false;
                isNeedRestartScript = checkOperStatusResult.script || false;
            } else {
                isNeedRestartWalletApp = false;
                isNeedRestartScript = false;
            }
        }

        if (isNeedRestartScript) {
            sleep(1 * 1000);
            // 清空控制台
            // console.clear();
            continue;
        }

        // 判断是否要重启app
        if (isNeedRestartWalletApp) {
            // 走关闭流程
            MomoFcfaAppOpen.closeMomoApp();

            // 走重启流程
            MomoFcfaAppOpen.openMomoApp();

            // 清空控制台
            // console.clear();
            continue;

        } else {

            // 判断是否为登录-手机号页
            if (isLoginPage) {
                // 清空控制台
                // console.clear();

                // 走登录-手机号流程
                let doLoginResult = MomoFcfaFunAction.doLogin();
                if (doLoginResult) {
                    // 判断是否为 pin 页
                    isPinPage = MomoFcfaPageUtil.doOpenLoginPinPage();
                }
            }

            // 判断是否为登录-PIN页
            if (isPinPage) {
                // 清空控制台
                // console.clear();

                // 走登录-PIN流程
                let doPinResult = MomoFcfaFunAction.doPin();
                if (doPinResult) {
                    // 判断是否为 首页
                    isHomePage = MomoFcfaPageUtil.doOpenHomePage();
                }
            }

            // 判断是否为首页
            if (isHomePage) {
                // 清空控制台
                // console.clear();

                // 获取转账信息
                cleanMtnTransfer();
                // -- temp close 放款
                if (false) {
                    let url = BaseApiUrl.getMtnTransferAccount();
                    let mtnAccountParams = { num: "1", phone: Constant.getMtn() }
                    let mtnAccountResult = BaseHttpUtil.sendPostSync(url, mtnAccountParams)
                    if (mtnAccountResult !== null) {
                        if (mtnAccountResult.length > 0) {
                            initMtnTransfer(mtnAccountResult[0]);
                        } else {
                            cleanMtnTransfer();
                        }
                    } else {
                        cleanMtnTransfer();
                    }

                    // 清空控制台
                    // console.clear();

                    // 打印转账信息
                    printMtnTransferLog();
                }

                // Test -- temp close 测试放款
                if (testTimes < 5) {
                    console.log("==== 测试放款");
                    initMtnTransfer({
                        id: "id_TEST_T1",
                        amount: Constant.TARGET_MTN_FCFA_AMOUNT,
                        mtn: Constant.TARGET_MTN_FCFA_MOBILE,
                        reference: Constant.TARGET_MTN_FCFA_REFERENCE
                    });
                    // 打印转账信息
                    printMtnTransferLog();
                }

                // 测试
                sleep(2000);
            }

            // 判断是否需要转账
            if (isValidMtnTransfer()) {
                console.log(Constant.UI_SDK_VERSION + "需要执行转账");

                // 走打开 Send Money 流程
                let doOpenSendMoneyPageResult = MomoFcfaFunAction.doOpenSendMoneyPage();
                if (doOpenSendMoneyPageResult) {
                    // 判断是否为 Send Money 页
                    isSendMoneyPage = MomoFcfaPageUtil.doOpenSendMoneyMtnPage();
                    if (isSendMoneyPage) {
                        isHomePage = false;
                    }
                }
                sleep(5000);
            }

            // 判断是否是 Send Money 页
            if (isSendMoneyPage && isValidMtnTransfer()) {
                console.log(Constant.UI_SDK_VERSION + "打开 Send Money 页");

                // 清空控制台
                // console.clear();
                isHomePage = false;

                // 走打开 To MTN MoMo 流程
                let doOpenMtnMoMoPageResult = MomoFcfaFunAction.doOpenMtnMoMoPage();
                if (doOpenMtnMoMoPageResult) {
                    // 判断是否为 To MTN MoMo 页
                    isMtnMoMoAccountInputPage = MomoFcfaPageUtil.doOpenSendMoneyMtnAccountInputPage()
                }
                sleep(5000);
            }

            // 判断是否为转账 Mtn account input 页
            if (isMtnMoMoAccountInputPage && isValidMtnTransfer()) {
                console.log(Constant.UI_SDK_VERSION + "打开 Send Money Account Input 页, 并执行转账操作");

                // 清空控制台
                // console.clear();
                isHomePage = false;

                // 开始转账流程
                let doMtnMoMoAccountInputResult = MomoFcfaFunAction.doMtnMoMoAccountInput(targetMtnTransferAccount, targetMtnTransferAmount, targetMtnTransferReference);
                if (doMtnMoMoAccountInputResult) {
                    // 判断是否为 Mtn MoMo account confirm 页
                    isMtnMoMoAccountConfirmPage = MomoFcfaPageUtil.doOpenSendMoneyMtnAccountConfirmPage();
                }
                sleep(5000);
            }

            // 判断是否为转账 Mtn account confirm 页
            if (isMtnMoMoAccountConfirmPage) {
                console.log(Constant.UI_SDK_VERSION + "打开 Send Money Confirm 页, 并执行确认转账操作");

                // 清空控制台
                // console.clear();
                isHomePage = false;

                // 点击确认
                let doClickTransferComletedResult = MomoFcfaFunAction.doClickTransferComleted();
                if (doClickTransferComletedResult) {
                    // 判断是否为 Mtn MoMo transfer success/fail 页
                    let sendResult = MomoFcfaPageUtil.doOpenSendMoneyMtnResultPage();
                    isMtnMoMoTransferSuccessPage = sendResult.isSuccess;
                    isMtnMoMoTransferFailPage = sendResult.isFail;
                    isHomePage = false;
                }
                sleep(5000);
            }

            // 判断是否为转账 Mtn momo transfer success 页
            if (isMtnMoMoTransferSuccessPage) {
                console.log(Constant.UI_SDK_VERSION + "打开 Send Money Success 页, 确认转账成功");

                // 清空控制台
                // console.clear();

                isMtnMoMoTransferFailPage = false;
                isHomePage = false;

                // 保存转账成功 -- temp close
                if (false) {
                    let url = BaseApiUrl.saveMtnTransferResult();
                    let mtnTransferResultParams = { id: targetMtnTransferId, response: "", status: "2", txnId: "" }
                    BaseHttpUtil.sendPostSync(url, mtnTransferResultParams)
                    sleep(1 * 1000);
                }

                // 清空转账信息
                cleanMtnTransfer();

                // 完成转账流程，返回 首页
                let doClickTransferDoneAndGoBackResult = MomoFcfaFunAction.doClickTransferDoneAndGoBack();
                if (doClickTransferDoneAndGoBackResult) {
                    console.log(Constant.UI_SDK_VERSION + "确认转账成功, 返回Send Money页");

                    // 判断是否为 Send Money 页
                    let isBacktoSendMoneyPage = MomoFcfaPageUtil.doOpenSendMoneyMtnPage();
                    if (isBacktoSendMoneyPage) {
                        console.log(Constant.UI_SDK_VERSION + "确认转账成功, 返回首页");

                        // 返回首页
                        back();
                        sleep(1 * 1000);
                        click(60, device.height - 60);
                        sleep(1000);
                    }
                }
                sleep(5000);
            }

            // 判断是否为转账 Mtn momo transfer fail 页
            if (isMtnMoMoTransferFailPage) {
                console.log(Constant.UI_SDK_VERSION + "打开 Send Money Fail 页, 确认转账失败");

                // 清空控制台
                // console.clear();

                isMtnMoMoTransferSuccessPage = false;
                isHomePage = false;

                // 保存转账失败 -- temp close
                if (false) {
                    let url = BaseApiUrl.saveMtnTransferResult();
                    let mtnTransferResultParams = { id: targetMtnTransferId, response: "", status: "3", txnId: "" }
                    BaseHttpUtil.sendPostSync(url, mtnTransferResultParams)
                    sleep(1 * 1000);
                }

                // 清空转账信息
                cleanMtnTransfer();

                // 完成转账流程，返回 首页
                let doClickTransferDoneAndGoBackResult = MomoFcfaFunAction.doClickTransferDoneAndGoBack();
                if (doClickTransferDoneAndGoBackResult) {
                    console.log(Constant.UI_SDK_VERSION + "确认转账失败, 返回Send Money页");

                    // 判断是否为 Send Money 页
                    let isBacktoSendMoneyPage = MomoFcfaPageUtil.doOpenSendMoneyMtnPage();
                    if (isBacktoSendMoneyPage) {
                        console.log(Constant.UI_SDK_VERSION + "确认转账失败, 返回首页");

                        // 返回首页
                        back();
                        sleep(1 * 1000);
                        click(60, device.height - 60);
                        sleep(1000);
                    }
                }

                // 完成转账流程，需要重启
                sleep(5000);
                continue;
            }

            if (true) {
                sleep(5000);
                continue;
            }

            // 判断是否为 首页
            isHomePage = MomoFcfaPageUtil.doOpenHomePage();

            // 判断是否为首页
            if (isHomePage) {
                // 清空控制台
                // console.clear();

                let doClickTransacitonsResult = MomoFcfaFunAction.doClickTransacitons();
                if (doClickTransacitonsResult) {
                    // 清空控制台
                    // console.clear();

                    // 判断是否为 bill list 页
                    isBillListPage = MomoFcfaPageUtil.doOpenBillListPage();
                }
            }

            // 判断是否为 bill list 页
            if (isBillListPage) {
                // 清空控制台
                // console.clear();

                // 获取流程详情
                MomoFcfaFunAction.doGetBillDetails();

                // 清空控制台
                // console.clear();

                // 返回
                back();
                sleep(1 * 1000);

                // 上传短信
                BaseSmsUtil.syncSmsData();

                console.log(Constant.UI_SDK_VERSION + "上报结束, 12秒后重新查询")
                // --- temp close
                if (false) {
                    sleep(10 * 1000);
                }

                // 清空控制台
                // console.clear();

                continue;
            }
            sleep(1 * 1000);

            // 最后都不能匹配成功，
            // 走关闭流程
            MomoFcfaAppOpen.closeMomoApp();

            // 走重启流程
            MomoFcfaAppOpen.openMomoApp();

            // 清空控制台
            // console.clear();
        }
    }
}



